package cn.stylefeng.guns.modular.order.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.stylefeng.guns.modular.basic.model.params.*;
import cn.stylefeng.guns.modular.basic.model.result.*;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.sys.modular.system.entity.Role;
import cn.stylefeng.guns.sys.modular.system.service.*;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.DefaultAvatar;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.DateUtil2;
import cn.stylefeng.guns.modular.basic.entity.BasicAddress;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.order.entity.OrderPutDetailed;
import cn.stylefeng.guns.modular.order.entity.OrderTransport;
import cn.stylefeng.guns.modular.order.entity.OrderTransportDetailed;
import cn.stylefeng.guns.modular.order.entity.StorageTaskXlb;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportDetailedResult;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.model.result.tmsAnalysis;
import cn.stylefeng.guns.modular.order.service.OrderPutService;
import cn.stylefeng.guns.modular.order.service.OrderTransportDetailedService;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.modular.transport.model.params.TDispatchParam;
import cn.stylefeng.guns.modular.transport.model.params.TransportDispatchParam;
import cn.stylefeng.guns.modular.transport.model.result.TDispatchResult;
import cn.stylefeng.guns.modular.transport.model.result.TransportDispatchResult;
import cn.stylefeng.guns.modular.transport.service.TDispatchService;
import cn.stylefeng.guns.modular.transport.service.TransportDispatchService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.FileInfo;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;


/**
 * 货运订单表控制器
 */
@Controller
@RequestMapping("/orderTransport")
public class OrderTransportController extends BaseController {

    private String PREFIX = "/order/orderTransport";

    @Autowired
    private OrderTransportService orderTransportService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private BasicCarrierService basicCarrierService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicOperateService basicOperateService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private DictService dictService;

    @Autowired
    private OrderTransportDetailedService orderTransportDetailedService;

    @Autowired
    private OrderPutService orderPutService;

    @Autowired
    private TDispatchService tDispatchService;

    @Autowired
    private FileInfoService fileInfoService;

    private final ResourceLoader resourceLoader;

	@Value("${hxl.api.url}")
	private String hxlApiUrl;

    @Autowired
    public OrderTransportController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    private Lock lock = new ReentrantLock();

    /**
     * 去货运订单汇总统计页面
     */
    @RequestMapping("toOrderTransportCount")
    public String toOrderTransportCount(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/orderTransportCount.html";
    }

    /**
     * 货运订单汇总
     */
    @ResponseBody
    @RequestMapping("/orderTransportCount")
    public LayuiPageInfo orderTransportCount(OrderTransportParam orderTransportParam,String condition ,String startTime,String endTime) {
    	User user = userService.getcurrentUser();
    	orderTransportParam.setDeliverId(user.getDeliverId());
    	orderTransportParam.setDeptId(user.getDeptId());
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		orderTransportParam.setSetMentiontime("'"+startTime+"' and '"+endTime+"'");
		} else if (startTime == null && endTime == null){
			startTime = DateUtil.getDate();
			endTime = DateUtil.getDate();
    		orderTransportParam.setSetMentiontime("'"+startTime+"' and '"+endTime+"'");
		}
        return this.orderTransportService.findOrderTransportCountBySpec(orderTransportParam,condition,user.getOperateId());
    }

    /**
     * TMS使用情况
     */
    @RequestMapping("tmsAnalysis")
    public String tmsAnalysis(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();

    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/tmsAnalysis.html";
    }

    /**
     *查询 TMS使用情况
     */
    @ResponseBody
    @RequestMapping("/tmsAnalysislist")
    public LayuiPageInfo tmsAnalysislist(OrderTransportParam orderTransportParam,String condition ,String startTime,String endTime) {
    	User user = userService.getcurrentUser();
        orderTransportParam.setDeptId(user.getDeptId());
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		orderTransportParam.setUndertime("'"+startTime+"' and '"+endTime+"'");
		} else if (startTime == null && endTime == null){
			startTime = DateUtil.getDate();
			endTime = DateUtil.getDate();
			orderTransportParam.setUndertime("'"+startTime+"' and '"+endTime+"'");
		}
    	LayuiPageInfo layuiPageInfo = this.orderTransportService.findTmsAnalysislist(orderTransportParam,condition,user.getOperateId());
    	List<tmsAnalysis> list = layuiPageInfo.getData();
    	for (tmsAnalysis r : list) {
    		TDispatchParam tDispatchParam = new TDispatchParam();
    		tDispatchParam.setDeptId(r.getDeptId());
    		tDispatchParam.setStartDate("'"+startTime+"' and '"+endTime+"'");
    		TDispatchResult dispatchResult = tDispatchService.sumfulllvBySpec(tDispatchParam);
    		if(dispatchResult != null) {
    			r.setMzl(dispatchResult.getFulllv()+"%");
    			r.setYccs(dispatchResult.getYycc());
    		}
		}
    	layuiPageInfo.setData(list);
        return layuiPageInfo;
    }

    /**
     * 跳转到主页面
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/orderTransport.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
    	basicPutgoodsParam.setUnitCategory("SHIP");
    	basicPutgoodsParam.setDeptId(deptId);
    	List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam,user.getOperateId());
    	model.addAttribute("pglist", pglist);
        return PREFIX + "/import.html";
    }

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcelXlb")
    public String toimportExcelXlb(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));

    	BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
    	basicPutgoodsParam.setUnitCategory("SHIP");
    	basicPutgoodsParam.setDeptId(deptId);
    	List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam,user.getOperateId());
    	model.addAttribute("pglist", pglist);
        return PREFIX + "/importXlb.html";
    }

    /**
     * 拉取新零帮拣货任务页面
     */
    @RequestMapping("/topullxlbStoragetask")
    public String topullxlbStoragetask(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

    	BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
    	basicPutgoodsParam.setUnitCategory("SHIP");
    	basicPutgoodsParam.setDeptId(deptId);
    	List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam,user.getOperateId());
    	model.addAttribute("pglist", pglist);
        return PREFIX + "/pullxlbStoragetask.html";
    }

    @Autowired
    private BasicGoodsService basicGoodsService;

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    /**
     * 拉取新零帮拣货任务
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/pullxlbStoragetask")
    @ResponseBody
    public ResponseData pullxlbStoragetask(String modified_begin,String modified_end, Integer customerId,String setMentiontime,Long setUnitId) {
    	if(setUnitId == null) {
    		return ResponseData.error("请选择装货单位");
    	}
        String url = this.hxlApiUrl+"/hxl.open.wms.pickOrder.find";
//        String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.pickOrder.find";
        List<String> pick_finish_time = new ArrayList<String>();
        pick_finish_time.add(modified_begin);
        pick_finish_time.add(modified_end);
        BasicCustomer r = basicCustomerService.getById(customerId);

        if(ToolUtil.isEmpty(r.getStoreIdXlb())) {
    		return ResponseData.error("请维护新零帮发货门店id");
        }
        if(ToolUtil.isEmpty(r.getGsnumber())) {
    		return ResponseData.error("请维护新零帮公司号");
        }

    	BasicGoodsParam goodsParam = new BasicGoodsParam();
    	goodsParam.setGoodsCustomerId(r.getId());
    	goodsParam.setGoodsNumber("sp1");
    	BasicGoodsResult sp1 = basicGoodsService.findBySpec(goodsParam, null);//商品
    	if(sp1 == null) {
    		return ResponseData.error("请添加虚拟商品sp1");
    	}
    	goodsParam.setGoodsNumber("cl1");
    	BasicGoodsResult cl1 = basicGoodsService.findBySpec(goodsParam, null);//拆零商品
    	if(cl1 == null) {
    		return ResponseData.error("请添加拆零商品cl1");
    	}
    	BasicPutgoods fh = basicPutgoodsService.getById(setUnitId);
    	BasicAddressParam basicAddressParam = new BasicAddressParam();
    	basicAddressParam.setPutgoodsId(Long.parseLong(fh.getId().toString()));
    	BasicAddressResult addressResult = basicAddressService.findBySpec(basicAddressParam);
    	if(addressResult == null) {
    		return ResponseData.error("装货地址不存在！请维护");
    	}

		User user = userService.getcurrentUser();

		BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
		oauth2tokenParam.setDeliverId(r.getDeliverId());
		oauth2tokenParam.setGsnumber(r.getGsnumber());
		BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
		if(oauth2tokenResult != null) {
			if(ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
				JSONObject json = new JSONObject();
				json.put("store_id", r.getStoreIdXlb());
				if(ToolUtil.isNotEmpty(r.getNeedCheck())&&r.getNeedCheck().equals("1")) {
					json.put("check_finish_time", pick_finish_time);
				} else {
					json.put("pick_finish_time", pick_finish_time);
				}
//				json.put("pick_finish_time", pick_finish_time);
				String post = HttpRequest.post(url)
							.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//				System.out.println("================json："+json+"========================");
//				System.out.println("================post："+post+"========================");
		    	JSONObject jsonObject = new JSONObject(post);
				if(jsonObject.get("code").toString().equals("0")) {
			    	List<StorageTaskXlb> xlbs = new ArrayList<StorageTaskXlb>();
					JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
					for (Object object : jsonArray) {
						JSONObject jsonObject2 = new JSONObject(object.toString());
						StorageTaskXlb xlb = new StorageTaskXlb();

						String fid = jsonObject2.get("fid").toString();
						if (ToolUtil.isNotEmpty(fid)&&!fid.equals("null")) {//单据号
							xlb.setFid(fid);
						} else {
							continue;
						}

						String store_id = jsonObject2.get("store_id").toString();
						if (ToolUtil.isNotEmpty(store_id)) {//发货门店id
							xlb.setStoreId(store_id);
						}

						String store_name = jsonObject2.get("store_name").toString();
						if (ToolUtil.isNotEmpty(store_name)) {//发货门店名称
							xlb.setStoreName(store_name);
						}

						String storehouse_id = jsonObject2.get("storehouse_id").toString();
						if (ToolUtil.isNotEmpty(storehouse_id)) {//发货仓库id
							xlb.setStorehouseId(storehouse_id);
						}

						String storehouse_name = jsonObject2.get("storehouse_name").toString();
						if (ToolUtil.isNotEmpty(storehouse_name)) {//发货仓库名称
							xlb.setStorehouseName(storehouse_name);
						}

						String client_id = jsonObject2.get("client_id").toString();
						if (ToolUtil.isNotEmpty(client_id)) {//收货客户id
							xlb.setClientId(client_id);
						}

						String client_name = jsonObject2.get("client_name").toString();
						if (ToolUtil.isNotEmpty(client_name)&&!client_name.equals("null")) {//客户名称
							xlb.setClientName(client_name);
						} else {
							continue;
						}

						String client_province_name = jsonObject2.get("client_province_name").toString();
						if (ToolUtil.isNotEmpty(client_province_name)&&!client_province_name.equals("null")) {//省
							xlb.setClientProvinceName(client_province_name);
						}

						String client_city_name = jsonObject2.get("client_city_name").toString();
						if (ToolUtil.isNotEmpty(client_city_name)&&!client_city_name.equals("null")) {//市
							xlb.setClientCityName(client_city_name);
						}

						String client_district_name = jsonObject2.get("client_district_name").toString();
						if (ToolUtil.isNotEmpty(client_district_name)&&!client_district_name.equals("null")) {//区
							xlb.setClientDistrictName(client_district_name);
						}

						String client_address = jsonObject2.get("client_address").toString();
						if (ToolUtil.isNotEmpty(client_address)&&!client_address.equals("null")) {//地址
							xlb.setClientAddress(client_address);
						}

						String item_count = jsonObject2.get("item_count").toString();
						if (ToolUtil.isNotEmpty(item_count)&&!item_count.equals("null")){//商品数
							xlb.setItemCount(item_count);
						} else {
							continue;
						}

						String quantity = jsonObject2.get("quantity").toString();
						if (ToolUtil.isNotEmpty(quantity)&&!quantity.equals("null")){//应拣数量
							xlb.setQuantity(quantity);
						} else {
							continue;
						}

						String volume = jsonObject2.get("volume").toString();
						if (ToolUtil.isNotEmpty(volume)){//体积
							xlb.setVolume(volume);
						}

						String state = jsonObject2.get("state").toString();
						if (ToolUtil.isNotEmpty(state)){//
							xlb.setState(state);
						}

						String order_type = jsonObject2.get("order_type").toString();
						if (ToolUtil.isNotEmpty(order_type)){//
							xlb.setOrderType(order_type);
						}

						String create_by = jsonObject2.get("create_by").toString();
						if (ToolUtil.isNotEmpty(create_by)){//制单人
							xlb.setCreateBy(create_by);
						}

						String create_time = jsonObject2.get("create_time").toString();
						if (ToolUtil.isNotEmpty(create_time)){//制单时间
							xlb.setCreateTime(create_time);
						}

						String out_application_order_fid = jsonObject2.get("out_application_order_fid").toString();
						if (ToolUtil.isNotEmpty(out_application_order_fid)){//关联出库申请单
							xlb.setOutApplicationOrderFid(out_application_order_fid);
						}

						String demolition = jsonObject2.get("demolition").toString();
						if (ToolUtil.isNotEmpty(demolition)){//是否拆零
							xlb.setDemolition(demolition);
						}

						String delivery_date = jsonObject2.get("delivery_date").toString();
						if (ToolUtil.isNotEmpty(delivery_date)){//配送日期
							xlb.setDeliveryDate(delivery_date);
						}

						String pallets = jsonObject2.get("pallets").toString();
						if (ToolUtil.isNotEmpty(pallets)&&!pallets.equals("null")){//托盘号
							OrderTransportParam ch = new OrderTransportParam();
							ch.setCustomerOrder(pallets+"_"+fid);
							OrderTransportResult chr = this.orderTransportService.checkyouwu(ch);
							if(chr != null) {
								continue;
							}
							xlb.setPallets(pallets);
						} else {
							continue;
						}

						String check_finish_time2 = jsonObject2.get("check_finish_time").toString();
						if (ToolUtil.isNotEmpty(check_finish_time2)){//质检完成时间
							xlb.setCheckFinishTime(check_finish_time2);
						}

						String channel_name = jsonObject2.get("channel_name").toString();
						if (ToolUtil.isNotEmpty(channel_name)){//通道号
							xlb.setChannelName(channel_name);
						}

						if(ToolUtil.isNotEmpty(demolition)&&demolition.equals("true")) {
							String box_count = jsonObject2.get("box_count").toString();
							if (ToolUtil.isNotEmpty(box_count)&&!box_count.equals("null")){//封箱拆零数
								xlb.setBoxCount(box_count);
							}
						}

						xlbs.add(xlb);
					}
					if(xlbs.size()>0) {
						List<OrderTransportParam> transportList = new ArrayList<OrderTransportParam>();//批量保存的 货运订单list
						List<OrderTransportDetailedParam> transportdList = new ArrayList<OrderTransportDetailedParam>();//批量保存的 货运订单list
						BasicOperate basicOperate = basicOperateService.getById(r.getCustomerOperateId());//分公司信息
						Long DeptId = r.getDeptId();
						Long DeliverId = r.getDeliverId();
						String trayCode = "HX";
						String name = "系统";

						if(user != null && ToolUtil.isNotEmpty(user.getName())){
							name = user.getName();
						}

						BigDecimal as = new BigDecimal("0");
						for (StorageTaskXlb xlb : xlbs) {
							OrderTransportParam addp = new OrderTransportParam();
							addp.setOperateId(Long.parseLong(r.getCustomerOperateId().toString()));//分公司id
							addp.setOperateName(basicOperate.getOperateName());//公司名称
							addp.setCustomerOrder(xlb.getPallets()+"_"+xlb.getFid());
							addp.setTransportNumber(trayCode+"HY"+cn.stylefeng.guns.core.util.DateUtil.getDatesBch()+cn.stylefeng.guns.core.util.DateUtil.getRandomNumber());
							addp.setOrderNumber(xlb.getFid());
							addp.setXlbClientId(xlb.getClientId());
							if(ToolUtil.isNotEmpty(xlb.getDemolition())&&xlb.getDemolition().equals("true")) {
								addp.setDemolition("拆零");
								addp.setPieceNumber(xlb.getBoxCount());
							}
							addp.setOrderSource("新零帮");
							addp.setCustomerId(Long.parseLong(r.getId().toString()));//客户id
							addp.setCustomerName(r.getCustomerName());//客户名称
							addp.setUndertime(DateUtil2.getDateS());//下单时间
							addp.setSetMentiontime(setMentiontime);//发货日期
							addp.setStockPort(xlb.getChannelName());

							addp.setSetUnit(fh.getPutgoodsName());//装货单位
							addp.setSetUnitId(Long.parseLong(fh.getId().toString()));//装货单位id
							addp.setSetLocation(addressResult.getAddress());//装货地址
							addp.setSetLocationId(Long.parseLong(addressResult.getId().toString()));//装货地址id
							addp.setSetPeople(addressResult.getContacts());//联系人
							addp.setSetTel(addressResult.getTel());//联系电话

					        toDealWith4(addp,r,xlb);//处理单位和地址

							addp.setDeptId(DeptId);
					    	addp.setDeliverId(DeliverId);
					    	addp.setCreateName(name);
					    	addp.setCreateTime(new Date());
					    	addp.setGoodsNum(xlb.getItemCount());
							addp.setTstate("PENDING_SUBMIT");

					    	//新增货运明细
							OrderTransportDetailedParam outTranDetailed = new OrderTransportDetailedParam();

							BigDecimal onum = new BigDecimal(xlb.getQuantity()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
							if(onum.compareTo(as) != 1) {
								continue;
							}
							if (ToolUtil.isNotEmpty(xlb.getVolume())) {
								BigDecimal v = new BigDecimal(xlb.getVolume()).setScale(4, BigDecimal.ROUND_HALF_DOWN);
								outTranDetailed.setGoodsVolume(v.divide(onum,4,BigDecimal.ROUND_HALF_DOWN).toString());
								outTranDetailed.setTransportPutvolume(xlb.getVolume());
							}  else {
								outTranDetailed.setGoodsVolume("1");
								outTranDetailed.setTransportPutvolume(onum.toString());
							}
							outTranDetailed.setGoodsWeight("1");
							outTranDetailed.setTransportWeight(onum.toString());

							outTranDetailed.setUnitprice("1");
							outTranDetailed.setTransportMoney(onum.toString());

							outTranDetailed.setTransportNumber(addp.getTransportNumber());

							if(xlb.getDemolition().equals("true")) {
								outTranDetailed.setGoodsName(cl1.getGoodsName());
								outTranDetailed.setGoodId(Long.parseLong(cl1.getId().toString()));
								outTranDetailed.setGoodsNumber(cl1.getGoodsNumber());
								outTranDetailed.setGoodsNo(cl1.getGoodsNo());
								outTranDetailed.setRebubbles(cl1.getGoodsHeavybubble());
								outTranDetailed.setDpacking(cl1.getGoodsPacking());
								outTranDetailed.setLargeclass(cl1.getGoodsBigtype());
								outTranDetailed.setGoodstype(cl1.getGoodsType());
								outTranDetailed.setConditions(cl1.getGoodsCondition());
								outTranDetailed.setGoodsUnit(cl1.getGoodsUnit());
								outTranDetailed.setGoodsSpecs(cl1.getGoodsSpecs());
							} else {
								outTranDetailed.setGoodsName(sp1.getGoodsName());
								outTranDetailed.setGoodId(Long.parseLong(sp1.getId().toString()));
								outTranDetailed.setGoodsNumber(sp1.getGoodsNumber());
								outTranDetailed.setGoodsNo(sp1.getGoodsNo());
								outTranDetailed.setRebubbles(sp1.getGoodsHeavybubble());
								outTranDetailed.setDpacking(sp1.getGoodsPacking());
								outTranDetailed.setLargeclass(sp1.getGoodsBigtype());
								outTranDetailed.setGoodstype(sp1.getGoodsType());
								outTranDetailed.setConditions(sp1.getGoodsCondition());
								outTranDetailed.setGoodsUnit(sp1.getGoodsUnit());
								outTranDetailed.setGoodsSpecs(sp1.getGoodsSpecs());
							}

							outTranDetailed.setBalenum(onum.toString());
							outTranDetailed.setNum(onum.toString());

							outTranDetailed.setNotnum(onum.toString());
							outTranDetailed.setNotvolume(outTranDetailed.getTransportPutvolume());
							transportdList.add(outTranDetailed);

				    		transportList.add(addp);
						}
						if(transportList.size() > 0) {
							this.orderTransportService.saveBatchList(transportList);
							this.orderTransportDetailedService.saveBatchList(transportdList);
						}
					}
				}
			}
		}
		return ResponseData.success();
    }
	
	private void toDealWith4(OrderTransportParam addp, BasicCustomer r, StorageTaskXlb xlb) {
        //查询卸货单位 是否存在
    	BasicPutgoods bpgp3 = new BasicPutgoods();
        bpgp3.setPutgoodsCustomerId(r.getId());//客户id
        bpgp3.setPutgoodsName(xlb.getClientName());//单位名称 
        BasicPutgoods bputr2  = basicPutgoodsService.lambdaQuery()
        .eq(BasicPutgoods::getPutgoodsCustomerId, r.getId())
        .eq(BasicPutgoods::getPutgoodsName, xlb.getClientName())
        .last("LIMIT 1")
        .one();
        if (bputr2==null) {
        	bpgp3.setPutgoodsOperateName(r.getCustomerName());//客户名称
        	bpgp3.setDeliverId(r.getDeliverId());
        	bpgp3.setDeptId(r.getDeptId());
        	basicPutgoodsService.save(bpgp3);
        	addp.setGetUnit(xlb.getClientName());//卸货单位
        	addp.setGetUnitId(Long.parseLong(bpgp3.getId().toString()));//卸货单位id
        	
			BasicAddress bap3 = new BasicAddress();
			bap3.setPutgoodsName(xlb.getClientName());
			bap3.setPutgoodsId(Long.parseLong(bpgp3.getId().toString()));
			bap3.setSheng(xlb.getClientProvinceName());
			bap3.setShi(xlb.getClientCityName());
			bap3.setQu(xlb.getClientDistrictName());
			if(ToolUtil.isNotEmpty(xlb.getClientAddress())) {
				bap3.setAddress(xlb.getClientAddress());
			} else {
				bap3.setAddress(xlb.getClientName());
			}
			bap3.setLongitude("0");
			bap3.setLatitude("0");
			bap3.setSwitchWl("1");
			bap3.setSwitchBj("1500");//提货围栏半径 默认100米
			bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
			basicAddressService.save(bap3);
			addp.setGetLocationId(Long.parseLong(bap3.getId().toString()));//卸货地址id
			addp.setGetLocation(bap3.getAddress());//卸货地址
		} else {
			addp.setGetUnit(xlb.getClientName());//卸货单位
			addp.setGetUnitId(Long.parseLong(bputr2.getId().toString()));//卸货单位id
			//查询卸货地点 是否存在
			BasicAddress bap3 = new BasicAddress();
			bap3.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));//单位id
			BasicAddress bar2 = basicAddressService.lambdaQuery()
					.eq(BasicAddress::getPutgoodsId, bputr2.getId())
					.last("LIMIT 1")
					.one();
			
			if(bar2 != null) {
				addp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
				addp.setGetLocation(bar2.getAddress());//卸货地址
				addp.setGetPeople(bar2.getContacts());//联系人
				addp.setGetTel(bar2.getTel());//联系电话
				addp.setKilometer(bar2.getKilometer());
				addp.setLineId(bar2.getLineId());
				addp.setLineName(bar2.getLineName());
			} else {//如果没有地址 ，  卸货地址为 单位名称
				bap3.setSheng(xlb.getClientProvinceName());
				bap3.setShi(xlb.getClientCityName());
				bap3.setQu(xlb.getClientDistrictName());
				if(ToolUtil.isNotEmpty(xlb.getClientAddress())) {
					bap3.setAddress(xlb.getClientAddress());
				} else {
					bap3.setAddress(bputr2.getPutgoodsName());
				}
				bap3.setPutgoodsName(bputr2.getPutgoodsName());//单位名称
				bap3.setLongitude("0");
				bap3.setLatitude("0");
				bap3.setSwitchWl("1");
				bap3.setSwitchBj("1500");//提货围栏半径 默认100米
				bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
				basicAddressService.save(bap3);
				addp.setGetLocation(bap3.getAddress());//卸货地址
				addp.setGetLocationId(Long.parseLong(bap3.getId().toString()));//卸货地址id
			} 
		}
	}

	private void toDealWith41(OrderTransportParam addp, BasicCustomer r, StorageTaskXlb xlb) {
        //查询卸货单位 是否存在
        BasicPutgoodsParam bpgp3 = new BasicPutgoodsParam();
        bpgp3.setPutgoodsCustomerId(r.getId());//客户id
        bpgp3.setPutgoodsName(xlb.getClientName());//单位名称
        BasicPutgoodsResult bputr2 = basicPutgoodsService.findBySpec(bpgp3,null);
        if (bputr2==null) {
        	bpgp3.setPutgoodsOperateName(r.getCustomerName());//客户名称
        	bpgp3.setDeliverId(r.getDeliverId());
        	bpgp3.setDeptId(r.getDeptId());
        	basicPutgoodsService.add(bpgp3);
	        BasicPutgoodsParam bpgp4 = new BasicPutgoodsParam();
	        bpgp4.setPutgoodsCustomerId(r.getId());//客户id
	        bpgp4.setPutgoodsName(xlb.getClientName());//单位名称
	        bputr2 = basicPutgoodsService.findBySpec(bpgp4,null);
		}
        addp.setGetUnit(bputr2.getPutgoodsName());//卸货单位
        addp.setGetUnitId(Long.parseLong(bputr2.getId().toString()));//卸货单位id
        //查询卸货地点 是否存在
        BasicAddressParam bap3 = new BasicAddressParam();
        bap3.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));//单位id
        BasicAddressResult bar2 = basicAddressService.findBySpec(bap3);//通过单位id 地址 查询
        if(bar2 != null) {
        	addp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
        	addp.setGetLocation(bar2.getAddress());//卸货地址
        	addp.setGetPeople(bar2.getContacts());//联系人
        	addp.setGetTel(bar2.getTel());//联系电话
        	addp.setKilometer(bar2.getKilometer());
        	addp.setLineId(bar2.getLineId());
        	addp.setLineName(bar2.getLineName());
        } else {//如果没有地址 ，  卸货地址为 单位名称
        	bap3.setSheng(xlb.getClientProvinceName());
        	bap3.setShi(xlb.getClientCityName());
        	bap3.setQu(xlb.getClientDistrictName());
        	if(ToolUtil.isNotEmpty(xlb.getClientAddress())) {
            	bap3.setAddress(xlb.getClientAddress());
        	} else {
            	bap3.setAddress(bputr2.getPutgoodsName());
        	}
			bap3.setPutgoodsName(bputr2.getPutgoodsName());//单位名称
			bap3.setLongitude("0");
			bap3.setLatitude("0");
			bap3.setSwitchWl("1");
			bap3.setSwitchBj("1500");//提货围栏半径 默认100米
			bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
			basicAddressService.add(bap3);
	        BasicAddressParam bap4 = new BasicAddressParam();
	        bap4.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));
        	bap4.setAddress(xlb.getClientName());
        	bar2 = basicAddressService.findBySpec(bap4);
        	addp.setGetLocation(bar2.getAddress());//卸货地址
        	addp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
        	addp.setGetPeople(bar2.getContacts());//联系人
        	addp.setGetTel(bar2.getTel());//联系电话
		}
	}

    /**
     * 下载出库订单模板
     * @author zhucx
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate")
    public void downloadExcelTemplate(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/orderTransport.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Freight Order Template" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传excel
     */
	@RequestMapping(value = "/importExce" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file,OrderTransportParam orderTransportParam)  {
		ResponseData data = new ResponseData();
		lock.lock();//获取锁
		try {
			data = orderTransportService.getExceldata(file,orderTransportParam,data);//处理导入数据
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    /**
     * 审核List页面
     */
    @RequestMapping("toexamine")
    public String toexamine() {
        return PREFIX + "/examine.html";
    }

    /**
     * 调度查询页面
     */
    @RequestMapping("todispatch")
    public String todispatch(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/dispatch.html";
    }

    /**
     * 货运订单查询页面
     * @param model
     * @return
     */
    @RequestMapping("toQuery")
    public String toPrint(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/orderTransportQuery.html";
    }

    /**
     * 审核页面
     */
    @RequestMapping("/toaudit")
    public String toaudit(OrderTransportParam orderTransportParam,Model model) {
    	OrderTransport orderTransport = orderTransportService.getById(orderTransportParam.getId());
    	model.addAttribute("orderTransport", orderTransport);
        return PREFIX + "/orderTransport_audit.html";
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add(Model model) {
    	prepare(model);
        return PREFIX + "/orderTransport_add.html";
    }

    private void prepare(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择分公司
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
	}

	/**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
    	prepare(model);
        return PREFIX + "/orderTransport_edit.html";
    }

	/**
     * 选择单位页面
     */
    @RequestMapping("/toChoiceUnit")
    public String toChoiceUnit() {
        return PREFIX + "/choiceUnit.html";
    }

	/**
     * 选择地址页面
     */
    @RequestMapping("/toAddress")
    public String toAddress() {
        return PREFIX + "/address.html";
    }

    @Autowired
    private BasicAddressService basicAddressService;

	@Autowired
    private DeptService deptService;

	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(OrderTransportParam or) {
    	ResponseData data = new ResponseData();
    	//校验客户单号 是否存在
    	if (this.orderPutService.checkCustomerOrder(or.getCustomerOrder())) {
    		data.setSuccess(false);
    		data.setMessage("Customer Order Number Already Exists");
    		return data;
		} else {
    		data.setSuccess(true);
		}

        if(or!=null){
        	String getUnit = or.getGetUnit();
        	String getLocation = or.getGetLocation();
        	String setUnit = or.getSetUnit();
        	String setLocation = or.getSetLocation();
        	//解决参数中的 英文括号
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
        		or.setGetUnit(getUnit);
        	}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
        		or.setGetLocation(getLocation);
        	}
        	if (setUnit!=null&&setUnit!="") {
        		setUnit = setUnit.replace("& #40;", "(");
        		setUnit = setUnit.replace("& #41;", ")");
        		or.setSetUnit(setUnit);
        	}
        	if (setLocation!=null&&setLocation!="") {
        		setLocation = setLocation.replace("& #40;", "(");
        		setLocation = setLocation.replace("& #41;", ")");
        		or.setSetLocation(setLocation);
        	}
        }

        User user = userService.getcurrentUser();
        BasicAddress basicAddress = basicAddressService.getById(or.getGetLocationId());
        if(basicAddress != null) {
        	or.setKilometer(basicAddress.getKilometer());
        	or.setLineId(basicAddress.getLineId());
        	or.setLineName(basicAddress.getLineName());
        }
    	or.setTstate("PENDING_SUBMIT");//订单状态
    	or.setDeliverId(user.getDeliverId());
    	or.setDeptId(user.getDeptId());
		String trayCode = getOperateIdOrderPrefix(user);
    	if (or.getOperateId()!=null) {
    		BasicOperate o = basicOperateService.getById(or.getOperateId());
    		or.setOperateName(o.getOperateName());//分公司名称
		}
    	if (or.getCustomerId()!=null) {
    		BasicCustomer c = basicCustomerService.getById(or.getCustomerId());
    		or.setCustomerName(c.getCustomerName());//客户名称
		}
    	or.setCreateName(user.getName());//制单名称
    	OrderTransport t = this.orderTransportService.findByThelastone();
    	if (t!=null) {
    		or.setTransportNumber(trayCode+"-"+"HY-"+DateUtil.getDateBch()+"-"+(t.getId()+1));
		} else {
    		or.setTransportNumber(trayCode+"-"+"HY-"+DateUtil.getDateBch()+"-1");
		}
        this.orderTransportService.add(or);

        if(ToolUtil.isNotEmpty(or.getGetPeople()) || ToolUtil.isNotEmpty(or.getGetTel())) {
        	BasicAddressParam addressParam = new BasicAddressParam();
        	addressParam.setId(Integer.parseInt(or.getGetLocationId().toString()));
            if(ToolUtil.isNotEmpty(or.getGetPeople())) {
            	addressParam.setContacts(or.getGetPeople());
            }
            if(ToolUtil.isNotEmpty(or.getGetTel())) {
            	addressParam.setTel(or.getGetTel());
            }
        	basicAddressService.update(addressParam);
        }
        return ResponseData.success();
    }

    /**
     * 批量提交
     */
    @RequestMapping("/submission")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class,timeout=100)
    public ResponseData submission(@RequestParam("ids") Long[] ids) {
		User user  = userService.getcurrentUser();
		lock.lock();//获取锁
		try {
			for (Long id : ids) {
				OrderTransportParam param = new OrderTransportParam();
				param.setId(Integer.parseInt(id.toString()));
		    	OrderTransportResult orderTransportResult = orderTransportService.findSumBySpec(param);
		    	if (!"PENDING_SUBMIT".equals(orderTransportResult.getTstate())&&!"REVOKED".equals(orderTransportResult.getTstate())) {
		            continue;
				}
				QueryWrapper<OrderTransportDetailed> queryWrapper = new QueryWrapper<OrderTransportDetailed>();
				queryWrapper.eq("transport_number", orderTransportResult.getTransportNumber());
				int count = orderTransportDetailedService.count(queryWrapper);
	    		if (count==0) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
					return ResponseData.error("Please add commodity details first, Order No.:"+orderTransportResult.getTransportNumber());
				}
	    		param.setSubmitTime(new Date());
	    		param.setSubmitUser(user.getUserId());
	    		param.setSubmitName(user.getName());
				param.setTooNum("0");
				param.setTooVolume("0");
				param.setTotalNum(orderTransportResult.getTotalNum());
				param.setTotalVolume(orderTransportResult.getTotalVolume());
				param.setTstate("PENDING_TRANSFER");
		        orderTransportService.update(param);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
        return ResponseData.success();
    }

    /**
     * 批量作废
     */
    @RequestMapping("/tovoid")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class)
    public ResponseData tovoid(@RequestParam("ids") Long[] ids) {
    	for (Long id :ids) {
    		try {
        		OrderTransport orderTransport = orderTransportService.getById(id);
        		orderTransport.setTstate("CANCELLED");

    			OrderTransportParam param = new OrderTransportParam();
    	        ToolUtil.copyProperties(orderTransport,param);
    	        orderTransportService.update(param);
			} catch (Exception e) {
				break;
			}
		}
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(OrderTransportParam orderTransportParam) {
    	ResponseData data = new ResponseData();
    	//校验客户单号 是否存在
    	OrderTransport orderTransport = orderTransportService.getById(orderTransportParam.getId());
    	if(!orderTransport.getCustomerOrder().equals(orderTransportParam.getCustomerOrder())) {
    		if (this.orderPutService.checkCustomerOrder(orderTransportParam.getCustomerOrder())) {
    			data.setSuccess(false);
    			data.setMessage("Customer Order Number Already Exists");
    			return data;
    		} else {
    			data.setSuccess(true);
    		}
    	}
        if(orderTransportParam!=null){
        	String getUnit = orderTransportParam.getGetUnit();
        	String getLocation = orderTransportParam.getGetLocation();
        	String setUnit = orderTransportParam.getSetUnit();
        	String setLocation = orderTransportParam.getSetLocation();
        	//解决参数中的 英文括号
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
        		orderTransportParam.setGetUnit(getUnit);
        	}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
        		orderTransportParam.setGetLocation(getLocation);
        	}
        	if (setUnit!=null&&setUnit!="") {
        		setUnit = setUnit.replace("& #40;", "(");
        		setUnit = setUnit.replace("& #41;", ")");
        		orderTransportParam.setSetUnit(setUnit);
        	}
        	if (setLocation!=null&&setLocation!="") {
        		setLocation = setLocation.replace("& #40;", "(");
        		setLocation = setLocation.replace("& #41;", ")");
        		orderTransportParam.setSetLocation(setLocation);
        	}
        }
    	if (orderTransportParam.getOperateId()!=null) {
    		BasicOperate o = basicOperateService.getById(orderTransportParam.getOperateId());
    		orderTransportParam.setOperateName(o.getOperateName());//分公司名称
		}
    	if (orderTransportParam.getCustomerId()!=null) {
    		BasicCustomer c = basicCustomerService.getById(orderTransportParam.getCustomerId());
    		orderTransportParam.setCustomerName(c.getCustomerName());//客户名称
		}
        BasicAddress basicAddress = basicAddressService.getById(orderTransportParam.getGetLocationId());
        if(basicAddress != null) {
        	orderTransportParam.setKilometer(basicAddress.getKilometer());
        	orderTransportParam.setLineId(basicAddress.getLineId());
        	orderTransportParam.setLineName(basicAddress.getLineName());
        }
        this.orderTransportService.update(orderTransportParam);

        if(ToolUtil.isNotEmpty(orderTransportParam.getGetPeople()) || ToolUtil.isNotEmpty(orderTransportParam.getGetTel())) {
        	BasicAddressParam addressParam = new BasicAddressParam();
        	addressParam.setId(Integer.parseInt(orderTransportParam.getGetLocationId().toString()));
            if(ToolUtil.isNotEmpty(orderTransportParam.getGetPeople())) {
            	addressParam.setContacts(orderTransportParam.getGetPeople());
            }
            if(ToolUtil.isNotEmpty(orderTransportParam.getGetTel())) {
            	addressParam.setTel(orderTransportParam.getGetTel());
            }
        	basicAddressService.update(addressParam);
        }
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(OrderTransportParam orderTransportParam) {
        this.orderTransportService.delete(orderTransportParam);
        return ResponseData.success();
    }

    /**
     * 审核货运订单
     */
    @RequestMapping("/audit")
    @ResponseBody
    public ResponseData audit(OrderTransportParam orderTransportParam,@RequestParam("whether") String whether) {
		lock.lock();//获取锁
		try {
	    	OrderTransport orderTransport = orderTransportService.getById(orderTransportParam.getId());
            if (!"PENDING_APPROVAL".equals(orderTransport.getTstate())) {
	            return ResponseData.success();
			}
			OrderTransportDetailedParam dParam = new OrderTransportDetailedParam();
			dParam.setTransportNumber(orderTransport.getTransportNumber());
			List<OrderTransportDetailedResult> list = orderTransportDetailedService.findListBySpec(dParam);
			User user  = userService.getcurrentUser();
			orderTransport.setAuditTime(new Date());//审核时间
			orderTransport.setAuditUser(user.getUserId());
			orderTransport.setAuditName(user.getName());//审核人名称
			if ("1".equals(whether)) {
				BigDecimal TotalNum = new BigDecimal(0);//货运单总数
				BigDecimal TotalVolume = new BigDecimal(0);//货运单总体积
				for (OrderTransportDetailedResult otdr : list) {
					BigDecimal num = new BigDecimal(otdr.getNum());
					BigDecimal transportPutvolume = new BigDecimal(otdr.getTransportPutvolume());
					BigDecimal nTotalNum = TotalNum.add(num);
					TotalNum = nTotalNum;
					BigDecimal nTotalVolume = TotalVolume.add(transportPutvolume);
					TotalVolume = nTotalVolume;
				}
				orderTransport.setTotalNum(TotalNum.toString());
				orderTransport.setTotalVolume(TotalVolume.toString());
				orderTransport.setTstate("PENDING_TRANSFER");
			} else if("2".equals(whether)) {
				orderTransport.setTstate("REJECTED");
			}
			orderTransport.setAuditnode(orderTransportParam.getAuditnode());
			OrderTransportParam param = new OrderTransportParam();
	        ToolUtil.copyProperties(orderTransport,param);
	        orderTransportService.update(param);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
        return ResponseData.success();
    }

    /**
     * 批量审核
     * 货运订单
     */
    @RequestMapping("/batchVia")
    @ResponseBody
    public ResponseData batchVia(@RequestParam("ids") Long[] ids) {
		lock.lock();//获取锁
		try {
			for (Long id : ids) {
		    	OrderTransport orderTransport = orderTransportService.getById(id);
		    	if (!"PENDING_AUDIT".equals(orderTransport.getTstate())) {
		            continue;
				}
				OrderTransportDetailedParam dParam = new OrderTransportDetailedParam();
				dParam.setTransportNumber(orderTransport.getTransportNumber());
				List<OrderTransportDetailedResult> list = orderTransportDetailedService.findListBySpec(dParam);
				User user  = userService.getcurrentUser();
				orderTransport.setAuditTime(new Date());//审核时间
				orderTransport.setAuditUser(user.getUserId());
				orderTransport.setAuditName(user.getName());//审核人名称
				BigDecimal TotalNum = new BigDecimal(0);//货运单总数
				BigDecimal TotalVolume = new BigDecimal(0);//货运单总体积
				for (OrderTransportDetailedResult otdr : list) {
					BigDecimal num = new BigDecimal(otdr.getNum());
					BigDecimal transportPutvolume = new BigDecimal(otdr.getTransportPutvolume());
					BigDecimal nTotalNum = TotalNum.add(num);
					TotalNum = nTotalNum;
					BigDecimal nTotalVolume = TotalVolume.add(transportPutvolume);
					TotalVolume = nTotalVolume;
				}
				orderTransport.setTotalNum(TotalNum.toString());
				orderTransport.setTotalVolume(TotalVolume.toString());
				orderTransport.setTstate("PENDING_TRANSFER");
				OrderTransportParam param = new OrderTransportParam();
		        ToolUtil.copyProperties(orderTransport,param);
		        orderTransportService.update(param);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
        return ResponseData.success();
    }

    /**
     * 发起
     */
    @RequestMapping("/launch")
    @ResponseBody
    public ResponseData launch(OrderTransportParam orderTransportParam) {
    	ResponseData data = new ResponseData();
    	OrderTransport orderTransport = orderTransportService.getById(orderTransportParam.getId());
    	orderTransportParam.setCustomerOrder(orderTransport.getCustomerOrder());
    	OrderTransportResult orderTransportResult = orderTransportService.findBySpec(orderTransportParam,null);
    	if (orderTransportResult!=null) {
    		data.setSuccess(false);
    		data.setMessage("Customer Order Number Already Exists	");
    		return data;
		}
    	orderTransport.setTstate("PENDING_SUBMIT");
        ToolUtil.copyProperties(orderTransport,orderTransportParam);
        orderTransportService.update(orderTransportParam);
        return ResponseData.success();
    }

    /**
     * 撤回
     */
    @RequestMapping("/revoke")
    @ResponseBody
    public ResponseData revoke(OrderTransportParam orderTransportParam) {
    	ResponseData data = new ResponseData();
    	OrderTransport orderTransport = orderTransportService.getById(orderTransportParam.getId());
    	data = orderTransportService.revokeS(orderTransport,data);
        return data;
    }

    /**
     * 批量撤回
     */
    @RequestMapping("/btnRevoke")
    @ResponseBody
    public ResponseData btnRevoke(Long ids[]) {
    	ResponseData data = new ResponseData();
    	for (Long id : ids) {
    		OrderTransport orderTransport = orderTransportService.getById(id);
    		data = orderTransportService.revokeS(orderTransport,data);
		}
        return data;
    }

    @Autowired
    TransportDispatchService TransportDispatchService;

    /**
     * 批量删除
     */
    @RequestMapping("/btnDelete")
    @ResponseBody
    public ResponseData btnDelete(Long ids[]) {
    	for (Long id : ids) {
    		OrderTransport orderTransport = orderTransportService.getById(id);
    		//查询  调度明细
    		if(!orderTransport.getTstate().equals("CANCELLED")) {
    			TransportDispatchParam param = new TransportDispatchParam();
    			param.setTransportNumber(orderTransport.getTransportNumber());
    			TransportDispatchResult r = TransportDispatchService.findBySpec(param);
    			if(r != null) {
    				return ResponseData.error("This freight order has been configured！"+orderTransport.getTransportNumber());
    			}
    		}
    		OrderTransportDetailedParam detailedParam = new OrderTransportDetailedParam();
    		detailedParam.setTransportNumber(orderTransport.getTransportNumber());
    		orderTransportDetailedService.deleteBySpec(detailedParam);

    		OrderTransportParam delete = new OrderTransportParam();
    		delete.setId(orderTransport.getId());
    		orderTransportService.delete(delete);
		}
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(OrderTransportParam orderTransportParam) {
        OrderTransport detail = this.orderTransportService.getById(orderTransportParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(OrderTransportParam orderTransportParam,String condition ) {
    	User user = userService.getcurrentUser();
    	orderTransportParam.setDeliverId(user.getDeliverId());
    	orderTransportParam.setDeptId(user.getDeptId());
    	orderTransportParam.setTstate("list");
        return this.orderTransportService.findPageBySpec(orderTransportParam,condition,user.getOperateId());
    }

    /**
     * 审核列表
     */
    @ResponseBody
    @RequestMapping("/examinelist")
    public LayuiPageInfo examinelist(OrderTransportParam orderTransportParam,String condition ) {
    	User user = userService.getcurrentUser();
    	orderTransportParam.setDeliverId(user.getDeliverId());
    	orderTransportParam.setDeptId(user.getDeptId());
    	orderTransportParam.setTstate("examine");
        return this.orderTransportService.findPageBySpec(orderTransportParam,condition,user.getOperateId());
    }

    /**
     * 调度列表
     */
    @ResponseBody
    @RequestMapping("/dispatchlist")
    public LayuiPageInfo dispatchlist(OrderTransportParam orderTransportParam,String condition ,String startTime,String endTime,String startTime2,String endTime2) {
    	User user = userService.getcurrentUser();
    	orderTransportParam.setDeliverId(user.getDeliverId());
    	orderTransportParam.setDeptId(user.getDeptId());
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		orderTransportParam.setUndertime("'"+startTime+"' and '"+endTime+"'");
		}
    	if (ToolUtil.isNotEmpty(startTime2) && ToolUtil.isNotEmpty(endTime2)) {
    		orderTransportParam.setSetMentiontime("'"+startTime2+"' and '"+endTime2+"'");
		} else if (startTime2 == null && endTime2 == null){
			startTime2 = DateUtil.getDate();
			endTime2 = DateUtil.getDate();
    		orderTransportParam.setSetMentiontime("'"+startTime2+"' and '"+endTime2+"'");
		}

		String roleId = user.getRoleId();
		if(ToolUtil.isNotEmpty(roleId)){
			for(String rId : roleId.split(",")){
				Role byId = roleService.getById(rId);
				if(byId != null && byId.getName().contains("承运商")){
					BasicCarrierParam param = new BasicCarrierParam();
					param.setUserId(user.getUserId());
					BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
					if(bySpec != null){
						orderTransportParam.setCarrierId(bySpec.getId());
					}else{
						orderTransportParam.setCarrierId(-1);
					}
				}
			}
		}
        return this.orderTransportService.dispatchlistPageBySpec(orderTransportParam,condition,user.getOperateId());
    }

    /**
     * 货运订单查询
     */
    @ResponseBody
    @RequestMapping("/query")
    public LayuiPageInfo query(OrderTransportParam orderTransportParam,String condition ,String startTime,String endTime ,String startTime2,String endTime2) {
    	User user = userService.getcurrentUser();
    	orderTransportParam.setDeliverId(user.getDeliverId());
    	orderTransportParam.setDeptId(user.getDeptId());
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		orderTransportParam.setUndertime("'"+startTime+"' and '"+endTime+"'");
		}
    	if (ToolUtil.isNotEmpty(startTime2) && ToolUtil.isNotEmpty(endTime2)) {
    		orderTransportParam.setSetMentiontime("'"+startTime2+"' and '"+endTime2+"'");
		} else if (startTime2 == null && endTime2 == null){
			startTime2 = DateUtil.getDate();
			endTime2 = DateUtil.getDate();
    		orderTransportParam.setSetMentiontime("'"+startTime2+"' and '"+endTime2+"'");
		}
        return this.orderTransportService.findByQuery(orderTransportParam,condition,user.getOperateId());
    }

    /**
     * 显示图片
     * @param fileId
     * @return
     */
    @RequestMapping("show")
    public ResponseEntity show(String fileId){
        if(fileId!=null&&fileId!=""){
            FileInfo fileInfo = fileInfoService.getById(fileId);
            String fileName=fileInfo.getFileName();
            fileInfo.getFilePath();
            try {
                // 由于是读取本机的文件，file是一定要加上的， path是在application配置文件中的路径
                //return ResponseEntity.ok(resourceLoader.getResource("file:" + path + fileName));
                if(fileInfo.getFilePath()!=null&&fileInfo.getFilePath()!=""){
                    if( !FileUtil.exist(fileInfo.getFilePath())){
                        return ResponseEntity.ok(Base64.decode(DefaultAvatar.BASE_64_No));
                    }
                    return ResponseEntity.ok(resourceLoader.getResource("file:" + fileInfo.getFilePath()));
                }else {
                    return ResponseEntity.ok(Base64.decode(DefaultAvatar.BASE_64_No));
                }
            } catch (Exception e) {
                return ResponseEntity.ok(Base64.decode(DefaultAvatar.BASE_64_No));
            }
        }else {
            return ResponseEntity.ok(Base64.decode(DefaultAvatar.BASE_64_No));
        }
    }

	@ResponseBody
	@RequestMapping("/orderMap")
	public LayuiPageInfo orderMap(){

		return this.orderTransportService.findAllOrder();
	}

}


